package com.caosy.grassthinkremote.service;

import cn.hutool.core.collection.CollUtil;
import com.caosy.grassthinkremote.common.BaseContext;
import com.caosy.grassthinkremote.common.GtrConstant;
import com.caosy.grassthinkremote.common.RespData;
import com.caosy.grassthinkremote.entity.Commodity;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    public RespData addCommodityToCart(Long commodityId, HttpServletRequest request) {
        //验证这个商品的id是否存在
        boolean isValidId = validCommodityId(commodityId);
        //取出用户信息
        String username = getUsername(request);
        //添加到购物车
        RLock rLock = redissonClient.getLock(GtrConstant.REDISSON_ADD_TO_CART_LOCK);
        boolean locked = false;
        try {
            locked = rLock.tryLock(10,10, TimeUnit.SECONDS);
            addToCart(commodityId,username);
        } catch (Exception e) {
            return RespData.getFailure("系统异常！");
        } finally {
            if (locked && rLock.isHeldByCurrentThread()) rLock.unlock();
        }

        return RespData.getSuccess("添加到购物车成功！");
    }

    private void addToCart(Long commodityId,String username) {
        //先查出这个username对应的购物车map
        Integer commodityNum = (Integer) redisTemplate.opsForHash().get(GtrConstant.REDIS_QUERY_COMMODITY_CART_PREFIX + username,commodityId);
        if (Objects.isNull(commodityNum)) commodityNum = 0;
        commodityNum++;
        redisTemplate.opsForHash().put(GtrConstant.REDIS_QUERY_COMMODITY_CART_PREFIX + username,commodityId,commodityNum);
    }

    private String getUsername(HttpServletRequest request) {
        String username = (String) BaseContext.get(GtrConstant.LOCAL_USERNAME_KEY);
        return username;
    }

    private boolean validCommodityId(Long commodityId) {
        //redis中查询所有商品
        List<Commodity> list = (List<Commodity>)redisTemplate.opsForValue().get(GtrConstant.REDIS_QUERY_COMMODITY_LIST_KEY);
        if (CollUtil.isEmpty(list)) list = CollUtil.newArrayList();
        //将对应的商品id做成list
        List<Long> ids = list.stream().map(Commodity::getId).collect(Collectors.toList());
        //判断是否包含这个id
        return ids.contains(commodityId);
    }
}
